from django.shortcuts import render,redirect
#from django.http import HttpRequest
# Create your views here.
from login.forms import LoginForm
from login.models import SiteUser


def index(request):
    pass
    return render(request,'login/index.html')

def login(request):
    if request.method == 'POST':
        login_form=LoginForm(request.POST)
        if login_form.is_valid():                                                                #判断账户和密码是否合法，图片验证
            username = login_form.cleaned_data.get('username')                                   #清洗空格，验证账户
            password = login_form.cleaned_data.get('password')                                   #清洗空格，验证密码
            user = SiteUser.objects.filter(name=username,password=password).first()
            if user:                                                                             #判断用户存不存在
               request.session['is_login'] = True
               request.session['user_id'] = user.id
               request.session['username'] = user.name
               return redirect('/index/')
            else:
               message='用户名或者密码错误'
               return render(request,'login/login.html',locals())                                #local是返还本地函数的意思，这里返还的是message
        else:
            message="登录信息不合法"
            return redirect(request,'login/login.html', locals())
    login_form=LoginForm()
    return render(request, 'login/login.html',locals())

def register(request):
    pass
    return render(request, 'login/register.html')


def logout(request):
    if request.session.get('is_login'):
        request.session.flush()                                 #情况session信息
    return redirect('/login/')                                  #重新定向到/login/界面
